<template>
  <div>
    <h1>记录模块</h1>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="实验记录" name="first">
        <el-form :inline="true" :model="ExpSearchForm">
          <el-form-item label="功能单元编号">
            <el-input v-model="ExpSearchForm.unitId" placeholder="请输入功能单元编号"></el-input>
          </el-form-item>
          <el-form-item label="功能单元名称">
            <el-input v-model="ExpSearchForm.unitName" placeholder="请输入功能单元名称"></el-input>
          </el-form-item>
          <el-form-item label="功能单元状态">
            <el-select v-model="ExpSearchForm.unitState" @change="searchSelect(ExpSearchForm.unitState)" multiple
                       placeholder="请选择">
              <el-option
                  v-for="item in StateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="SearchSubmit" icon="el-icon-search" size="small">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
            :data="Record"
            height="500"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="ExpId" sortable label="实验编号"></el-table-column>
          <el-table-column prop="UnitId" sortable label="功能单元编号"></el-table-column>
          <el-table-column prop="UnitName" sortable label="功能单元名称"></el-table-column>
          <el-table-column prop="UnitState" sortable label="功能单元状态"></el-table-column>
          <el-table-column prop="PIInfo" label="PI信息">
            <template #default="scope">
              <el-popover
                  placement="right"
                  :width="400"
                  trigger="click"
              >
                <template #reference>
                  <el-button size="mini" @click="ShowPIDetailsClick(scope.row)">详细信息</el-button>
                </template>
                <el-table :data="PIData">
                  <el-table-column width="100" property="PIId" label="编号"></el-table-column>
                  <el-table-column width="100" property="PIName" label="姓名"></el-table-column>
                  <el-table-column width="100" property="PITitle" label="职称"></el-table-column>
                  <el-table-column width="100" property="PIGender" label="性别"></el-table-column>
                </el-table>
              </el-popover>

            </template>

          </el-table-column>
          <el-table-column prop="CheckInfo" label="查验信息">
            <template #default="scope">

              <el-popover
                  placement="right"
                  :width="400"
                  trigger="click"
              >
                <template #reference>
                  <el-button size="mini" @click="ShowCheckLogDetailsClick(scope.row)">详细信息</el-button>
                </template>
                <el-table :data="CheckData">
                  <!--                  <el-table-column width="100" property="CheckLogID" label="查验编号"></el-table-column>-->
                  <el-table-column width="100" property="Checker" label="查验员"></el-table-column>
                  <el-table-column width="200" property="CheckTime" label="查验时间"></el-table-column>
                  <el-table-column width="100" property="CheckResult" label="查验结果"></el-table-column>
                </el-table>
              </el-popover>
            </template>

          </el-table-column>
          <!--          <el-table-column label="操作">-->
          <!--            <template #default="scope">-->
          <!--              <el-button-->
          <!--                  size="mini"-->
          <!--                  type="danger"-->
          <!--                  @click="RecordDelete(scope.$index, scope.row)"-->
          <!--                  icon="el-icon-delete">删除-->
          <!--              </el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>

      </el-tab-pane>

      <el-tab-pane label="用户登录记录" name="second">
        <el-form :inline="true" :model="LoginFormSearch">
          <el-form-item label="用户类型">
            <el-select v-model="LoginFormSearch.role" multiple placeholder="请选择用户类型"
                       @change="chooseRole(LoginFormSearch.role)">
              <el-option
                  v-for="item in UserOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="LoginFormSearch.userName" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="block">
              <span class="demonstration">选择时间&nbsp;</span>
              <el-date-picker
                  v-model="timeRange"
                  type="daterange"
                  format="YYYY-MM-DD"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :shortcuts="shortcuts"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="SearchLogSubmit(1)" icon="el-icon-search" size="small">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table
            :data="LoginRecord"
            height="500"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="LoginLabId" sortable label="登录编号"></el-table-column>
          <el-table-column prop="UserCategory" sortable label="用户类型"></el-table-column>
          <el-table-column prop="UserId" sortable label="用户编号"></el-table-column>
          <el-table-column prop="UserName" sortable label="用户名"></el-table-column>
          <el-table-column prop="LoginTime" sortable label="登录时间"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  icon="el-icon-delete">删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import {get} from "@/utils/http";

export default {
  name: "doLog",
  data() {
    return {
      activeName: 'first',
      checkList: [],
      value1: [],
      selectRoles: [],
      selectValues: [],
      StateOptions: [{
        value: '资源不足',
        label: '资源不足'
      }, {
        value: '数据有误',
        label: '数据有误'
      }, {
        value: '实验失败',
        label: '实验失败'
      }, {
        value: '暂被撤销',
        label: '暂被撤销'
      }, {
        value: '尚未开始',
        label: '尚未开始'
      }, {
        value: '查验完成',
        label: '查验完成'
      }, {
        value: '归还完成',
        label: '归还完成'
      }, {
        value: '实验完成',
        label: '实验完成'
      }],
      UserOptions: [{
        value: 'PI',
        label: '独立PI'
      }, {
        value: 'assistant',
        label: '科研助理'
      }],
      Record: [],
      PIData: [],
      CheckData: [
        // {
        //   Checker: '王五',
        //   CheckTime: '2021-07-13-20:25',
        //   CheckResult: '通过',
        // }
      ],
      LoginRecord: [],
      shortcuts: [{
        text: '最近一周',
        value: (() => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        })(),
      }, {
        text: '最近一个月',
        value: (() => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        })(),
      }, {
        text: '最近三个月',
        value: (() => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        })(),
      }],
      timeRange: '',
      InputUserCategory: '',
      LoginFormSearch: {
        userName: '',
        role: '',
      },
      ExpSearchForm: {
        unitId: '',
        unitName: '',
        unitState: '',
      }
    };
  },
  methods: {
    handleClick() {
      // console.log(tab, event);
    },
    handleDelete(row) { //第二个界面的删除
      let that = this;
      // 设置类似于console类型的功能
      that.$confirm("永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            // 移除对应索引位置的数据，可以对row进行设置向后台请求删除数据
            console.log("1111");
            console.log(row.LoginLabId);
            get('/loginLabLog/deleteInfo', {
              loginlab_id: row.LoginLabId,
            }).then(function (res) {
              console.log(res);
            })
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            // that.LoginRecord.splice(index, 1);
            that.SearchLogSubmit();
          })
          .catch(() => {
            that.$message({
              type: "info",
              message: "已取消删除"
            });
          });
    },
    chooseRole(value) {
      this.selectRoles = value;
    },
    SearchLogSubmit(val) {
      let that = this;
      let startDate = '';
      let endDate = '';
      that.LoginRecord = [];
      if(val===1){
        if(that.selectRoles.length===0){
          ElMessage.error({
            showClose: true,
            message: "请选择用户类型！",
            type: "error",
            center: true
          })
          return;
        }
        if(that.LoginFormSearch.userName===''){
          this.$notify({
            title: '提示',
            message: '您未输入用户名，将不限制查询的用户名',
            type: 'warning',
            customClass: 'backgroundClass',
          });
        }
      }

      console.log("5555");
      console.log(that.timeRange);
      if((that.timeRange===null || that.timeRange.length===0)&&val===1){
        console.log("666");
        this.timer = window.setTimeout(() => {
          this.$notify({
            title: '提示',
            message: '您未选择时间范围，将为您查询所有时间的数据',
            type: 'warning',
            customClass: 'backgroundClass',
          });
          startDate='';
          endDate='';
        }, 0)
      }
      else{
        that.timeRange.forEach(function (item, index) {
          var year = item.getFullYear(); //得到年份
          var month = item.getMonth();//得到月份
          var date = item.getDate();//得到日期
          if (index === 1) {
            date = date + 1;
          }
          month = month + 1;
          if (month < 10) month = "0" + month;
          if (date < 10) date = "0" + date;
          var timeStr = year + "-" + month + "-" + date;
          if (index === 0)
            startDate = timeStr;
          else
            endDate = timeStr;
        })
      }

      that.selectRoles.forEach(function (item) {
        get('/loginLabLog/getInfo', {
          username: that.LoginFormSearch.userName,
          role: item,
          start_time: startDate,
          end_time: endDate
        }).then(function (res) {
          res.data.forEach(function (tmp) {
            var role = '';
            if (tmp.role === 'checker') role = '查验员';
            else if (tmp.role === 'assistant') role = '科研助理';
            else if (tmp.role === 'PI') role = '独立PI';
            else if (tmp.role === 'logger') role = '记录维护员';
            var timeHere = new Date(tmp.loginlab_time);
            var year = timeHere.getFullYear(); //得到年份
            var month = timeHere.getMonth();//得到月份
            var date = timeHere.getDate();//得到日期
            var hour = timeHere.getHours();//得到日期
            var minute = timeHere.getMinutes();//得到日期
            var second = timeHere.getSeconds();//得到日期
            month = month + 1;
            if (month < 10) month = "0" + month;
            if (date < 10) date = "0" + date;
            if (hour < 10) hour = "0" + hour;
            if (minute < 10) minute = "0" + minute;
            if (second < 10) second = "0" + second;
            var timeHereStr = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;    //（格式化"yyyy-MM-dd"）
            // console.log(timeHereStr);
            var t = {
              LoginLabId: tmp.loginlab_id,
              UserCategory: role,
              UserId: tmp.uid,
              UserName: tmp.username,
              LoginTime: timeHereStr
            };
            that.LoginRecord.push(t);
          })
        })
      })
    },
    SearchSubmit() {
      let that = this;
      that.Record = [];
      if (that.ExpSearchForm.unitId.slice(0, 2) !== 'UN' && that.ExpSearchForm.unitId !== '') {
        ElMessage.warning({
          showClose: true,
          message: "功能单元编号应以UN开头！",
          type: "warning",
          center: true
        })
        return;
      }
      if (that.selectValues.length === 0) {
        ElMessage.error({
          showClose: true,
          message: "请选择功能单元状态！",
          type: "error",
          center: true
        })
        return;
      }
      if(that.ExpSearchForm.unitId===''){
        this.$notify({
          title: '提示',
          message: '您未输入功能单元编号，将不限制查询的功能单元编号',
          type: 'warning',
          customClass: 'backgroundClass',
        });
      }
      if(that.ExpSearchForm.unitName===''){
        this.timer = window.setTimeout(() => {
          this.$notify({
            title: '提示',
            message: '您未选择功能单元名称，将不限制查询的功能单元名称',
            type: 'warning',
            customClass: 'backgroundClass',
          });
        }, 0)
      }

      that.selectValues.forEach(function (item) {
        console.log(item);
        get('/proPartialInfo/getInfo', {
          exp_id: '',
          pro_id: that.ExpSearchForm.unitId,
          pro_name: that.ExpSearchForm.unitName,
          pro_state: item
        }).then(function (res) {
              if (res.code === 1) {
                console.log(res.data);
                res.data.forEach(function (item) {
                  var tmp = {
                    ExpId: item.exp_id,
                    UnitId: item.pro_id,
                    UnitName: item.pro_name,
                    UnitState: item.pro_state,
                    PIId: item.pi_id,
                    CheckLogId: item.checklog_id,
                  };
                  that.Record.push(tmp);
                })
              }
            }
        );
      })

    },
    searchSelect(value) {
      this.selectValues = value;
    },
    ShowPIDetailsClick(row) {
      let that = this;
      let tmp_piId = row.PIId;
      that.PIData = [];
      get('/piInfo/getInfo', {
        pi_id: tmp_piId
      }).then(function (res) {
            if (res.code === 1) {
              // console.log(res.data);
              res.data.forEach(function (item) {
                var tmp = {
                  PIId: item.pi_id,
                  PIName: item.pi_name,
                  PITitle: item.pi_title,
                  PIGender: item.pi_gender
                };
                that.PIData.push(tmp);
              })
            }
          }
      );
    },
    ShowCheckLogDetailsClick(row) {
      let that = this;
      let tmp_clId = row.CheckLogId;
      that.CheckData = [];
      Date.prototype.format = function (fmt) {
        var o = {
          "M+": this.getMonth() + 1,                 //月份
          "d+": this.getDate(),                    //日
          "h+": this.getHours(),                   //小时
          "m+": this.getMinutes(),                 //分
          "s+": this.getSeconds(),                 //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          }
        }

        return fmt;
      }
      get('/checkLog/getInfo', {
        checklog_id: tmp_clId
      }).then(function (res) {
            if (res.code === 1) {
              // console.log(res.data);
              res.data.forEach(function (item) {
                let time_str = item.check_time.slice(0, 19);
                time_str = time_str.replace('T', ' ');
                var tmp = {
                  Checker: item.checker_id,
                  CheckTime: time_str,
                  CheckResult: item.check_result
                };
                that.CheckData.push(tmp);
              })
            }
          }
      );
      // console.log(that.CheckData);
    }
  }
}
</script>

<style >
.backgroundClass{
  background-color: #fcf4e8;
}
</style>